'use strict';

const jwt = require('jsonwebtoken');
const { Controller } = require('egg');
const { Op } = require('sequelize');

class ClassController extends Controller {
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize, class_name,school_id } = query;
    const page = Number(pageNum) || 1;
    const size = Number(pageSize) || 10;
    const where = {
      class_name: { [Op.like]: `%${class_name}%`},
    };
    if (school_id) {
      where.school_id = school_id
    }
    const users = await service.class.getPage(where, page, size);
    this.ctx.success(users);
  }

  // 所有列表
  async allList() {
    const { query, service } = this.ctx;
    let { school_id, class_name } = query;
    let where = {};
    if (class_name) {
      where = {
        [Op.or]: [
          {
            class_name: { [Op.like]: `%${content}%` },
          },
        ]
      };
    }
    if (school_id) {
      where.school_id = school_id
    }
    const user = await service.class.allList(where);
    this.ctx.success(user);
  }

  // 删除用户
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service.class.deleteItemById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }

  // 修改用户信息
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递用户ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service.class.updateItemById(id, infos);
    ctx.success(id, 200);
  }

  // 创建新用户
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await ctx.service.class.createItem(data);
    ctx.success(res);
  }

  // 登录
  async login() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    const user = await service.class.loginByEmail(data);
    user.token = jwt.sign(user, this.config.keys);
    ctx.success(user);
  }

  // 修改密码
  async updatePassword() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    await service.class.updatePassword(ctx.class.id, data);
    ctx.success();
  }
}

module.exports = ClassController;
